<template>
  <el-container class="app-container">
    <zl-table ref="table" url="/sys/quartz/listJob" :param.sync="par" @selectChange="selectChange">
      <template slot="search">
        <el-form :inline="true" :model="par" class="left">
          <el-form-item label="任务名" prop="jobName">
            <el-input v-model="par.jobName" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" size="small" @click="query">搜 索</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template slot="toolbar">
        <el-row :gutter="10" class="mb10">
          <el-col :span="1.5">
            <el-button size="small" plain type="primary" icon="el-icon-plus" @click="addSetting">新 增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button class="ml10" plain size="small" type="danger" icon="el-icon-delete" @click="deleteTask">删 除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button class="ml10" plain size="small" type="primary" icon="el-icon-video-pause" @click="startTask">启 动</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button class="ml10" plain size="small" type="primary" icon="el-icon-video-play" @click="pauseTask">暂 停</el-button>
          </el-col>
          <el-col :span="1.5" class="fr">
            <el-tooltip :content="'服务状态: ' + (service ? '已启动' : '未启动')" placement="top">
              <el-switch v-model="service" :readonly="queryStatus" active-color="#409EFF" inactive-color="#ff4949" @change="switchService" />
            </el-tooltip>
          </el-col>
        </el-row>
      </template>
      <template slot="cols">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" width="50px" type="index" :index="indexMethod"/>
        <el-table-column fixed min-width="200px" prop="jobName" label="任务名" align="left" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="jobClassName" label="执行代码" min-width="150px" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="cronExpression" label="执行频率" min-width="100px" align="center" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="prevFireTime" label="上次自动执行" min-width="180px" align="center" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="nextFireTime" label="下次自动执行" min-width="180px" align="center" show-overflow-tooltip sortable="custom"/>
        <el-table-column prop="triggerState" label="状态" min-width="90px" align="center" show-overflow-tooltip sortable="custom"/>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              title="编辑"
              type="primary"
              circle
              plain
              class="el-icon-edit"
              size="mini"
              @click.native.prevent="editRow(scope.$index, scope.row)"
            />
            <el-button
              title="手动执行"
              type="primary"
              circle
              plain
              class="iconfont icon-yunwei"
              size="mini"
              @click.native.prevent="handExecute(scope.$index, scope.row)"
            />
            <el-button
              title="执行日志"
              type="primary"
              circle
              plain
              class="el-icon-tickets"
              size="mini"
              @click.native.prevent="showQuartzLogLog(scope.row)"
            />
          </template>
        </el-table-column>
      </template>
    </zl-table>
    <el-dialog :title="title" :visible.sync="show" :append-to-body="true" :close-on-click-modal="false" width="500px">
      <el-form ref="editForm" :model="form" :rules="rules" :label-width="labelWidth">
        <el-form-item label="任务名" prop="jobName" class="is-required">
          <el-input v-model="form.jobName" clearable autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="执行代码" prop="jobClassName" class="is-required">
          <el-input v-model="form.jobClassName" clearable autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="执行频率" prop="cronExpression" class="is-required">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-input v-model="form.cronExpression" clearable autocomplete="off" placeholder="请选择" readonly />
            </el-col>
            <el-col :span="1.5">
              <el-button class="ml5" plain circle icon="iconfont icon-shezhi" size="mini" type="primary" title="配置频率" @click="rate.show=true" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="loading" @click="saveOrg">保 存</el-button>
        <el-button size="small" @click="show = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="配置频率" :visible.sync="rate.show" :append-to-body="true" :close-on-click-modal="false" width="700px">
      <el-form ref="rateForm" :model="rate.form" label-width="80px">
        <el-collapse v-model="active" accordion>
          <el-collapse-item name="date" title="定期执行">
            <el-form-item label="" prop="week" class="is-required" label-width="0">
              <el-checkbox-group v-model="rate.form.week" @change="">
                <el-checkbox v-for="(o,i) in weeks" :key="i" :label="o.v">{{ o.l }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="" prop="week" class="is-required" label-width="0">
              <el-time-picker
                v-model="rate.form.time"
                format="HH:mm"
                value-format="HH:mm"
              />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item name="time">
            <template slot="title">
              定时执行 <el-popover
                placement="top-start"
                title="提示"
                trigger="hover"
              >
                <em class="red">*(如果配置了此项，则按此配置执行定时任务，上面的配置无效)</em>
                <i slot="reference" class="header-icon el-icon-info" />
              </el-popover>
            </template>
            <el-form-item label="" prop="minute" class="is-required" label-width="0">
              每隔<el-input-number v-model="rate.form.minute" class="m5" controls-position="right" :max="60" :min="1" style="width: 110px" />分钟
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="loading" @click="calcRate">保 存</el-button>
        <el-button size="small" @click="rate.show = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
import { validator } from '@/utils/form'
import ZlTable from '@/components/table/table-con'
import {
  deleteCronJob,
  getCronExpression,
  handExecuteJob,
  pauseCronJob,
  quartzStatus,
  saveCronJob,
  startCronJob, startQuartzService, stopQuartzService
} from '@/api/quartz'
export default {
  name: 'Setting',
  components: { ZlTable },
  data() {
    return {
      par: {
        jobName: ''
      },
      modules: [],
      form: {
        jobName: '', jobClassName: '', cronExpression: '', operator: 1
      },
      queryStatus: false,
      service: true,
      active: 'date',
      title: '修改定时任务',
      add: false,
      loading: false,
      show: false,
      showEncrypt: false,
      labelWidth: '80px',
      checkRow: [],
      weeks: [
        { v: 2, l: '周一' }, { v: 3, l: '周二' }, { v: 4, l: '周三' }, { v: 5, l: '周四' },
        { v: 6, l: '周五' }, { v: 7, l: '周六' }, { v: 1, l: '周一' }
      ],
      rate: {
        show: false,
        form: {
          week: [],
          time: '00:00',
          type: 0,
          minute: 1
        }
      }
    }
  },
  computed: {
    rules() {
      return {
        jobName: [
          { validator: validator('notBlank'), message: '任务名不能为空', trigger: ['blur', 'change'] }
        ],
        jobClassName: [
          { validator: validator('notBlank'), message: '执行代码不能为空', trigger: ['blur', 'change'] }
        ],
        cronExpression: [
          { validator: validator('notBlank'), message: '执行频率不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  watch: {
    'active': function(v) {
      console.log(v)
      this.rate.form.type = (v === 'date' ? 0 : 1)
    }
  },
  mounted() {
    this.queryQuartzStatus()
  },
  methods: {
    showQuartzLogLog(row){
      const jobName = row.jobName
      this.$router.push(`/quartzLog/${jobName}`)
    },
    queryQuartzStatus() {
      this.queryStatus = true
      quartzStatus().then(r => {
        this.service = r.data
        this.queryStatus = false
      }).catch(() => {
        this.service = false
        this.queryStatus = false
      })
    },
    switchService(v) {
      console.log('switchService', v)
      const s = v ? '打开' : '关闭'
      this.$confirm('确定要' + s + '定时任务吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        if (v) {
          startQuartzService().then(() => {
            this.$message.success('打开成功')
            this.queryQuartzStatus()
          })
        } else {
          stopQuartzService().then(() => {
            this.$message.success('关闭成功')
            this.queryQuartzStatus()
          })
        }
      }).catch(() => {
        console.log('操作失败')
        this.queryQuartzStatus()
      })
    },
    selectChange(v) {
      console.log('check', v)
      this.checkRow = v
    },
    saveOrg() {
      this.$refs.editForm.validate(r => {
        if (r) {
          this.loading = true
          saveCronJob(this.form).then((r) => {
            this.$message.success('保存成功')
            this.loading = false
            this.show = false
            this.query()
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    calcRate() {
      getCronExpression(this.rate.form).then((r) => {
        if (r.err) {
          this.$message.error(r.err)
        } else {
          this.form.cronExpression = r.data.time
          this.rate.show = false
          this.$message({
            dangerouslyUseHTMLString: true,
            message: r.data.executeTimeList
          })
        }
      })
    },
    setRate() {
      const timeValue = this.form.cronExpression
      if (timeValue) {
        const pos = timeValue.indexOf('?')
        if (timeValue.length === (pos + 1)) {
          if (timeValue.indexOf('/') !== -1) {
            const newval = timeValue.split('/')[1].split(' ')[0]
            this.rate.form.minute = newval
            this.rate.form.week = []
          } else {
            const valArray = timeValue.split(' ')
            const minute = valArray[1]
            const hour = valArray[2]
            this.rate.form.time = hour + ':' + minute
            this.rate.form.week = []
          }
        } else {
          const valArray = timeValue.split(' ')
          const minute = valArray[1]
          const hour = valArray[2]
          this.rate.form.time = hour + ':' + minute
          const weekval = timeValue.substr(timeValue.indexOf('?') + 4)
          const weeks = weekval.split(',')
          this.rate.form.week = []
          for (let k = 0; k < weeks.length; k++) {
            this.rate.form.week.push(parseInt(weeks[k]))
          }
        }
      }
    },
    addSetting() {
      this.title = '新增定时任务'
      this.show = true
      this.add = true
      this.showEncrypt = true
      this.form = { operator: 1 }
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    deleteTask() {
      if (this.checkRow.length === 0) {
        this.$message.warning('请选择定时任务')
        return
      }
      deleteCronJob(this.checkRow.map(o => o.jobName)).then((r) => {
        this.$message.success('删除成功')
        this.query()
      })
    },
    pauseTask() {
      if (this.checkRow.length === 0) {
        this.$message.warning('请选择定时任务')
        return
      }
      pauseCronJob(this.checkRow.map(o => o.jobName)).then((r) => {
        this.$message.success('暂停成功')
        this.query()
      })
    },
    startTask() {
      if (this.checkRow.length === 0) {
        this.$message.warning('请选择定时任务')
        return
      }
      startCronJob(this.checkRow.map(o => o.jobName)).then((r) => {
        this.$message.success('启动成功')
        this.query()
      })
    },
    handExecute(index, row) {
      handExecuteJob(row.jobName).then((r) => {
        this.$message.success('执行成功')
      })
    },
    editRow(index, row) {
      this.title = '修改定时任务'
      console.log(row)
      this.add = false
      this.form = this.$util.copy(row)
      this.form.operator = 0
      this.setRate()
      this.show = true
      this.showEncrypt = false
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    query() {
      this.$refs.table.query()
    },
    indexMethod(index) {
      return (this.$refs.table.pageNum - 1) * this.$refs.table.pageSize + index + 1
    }
  }
}
</script>
<style scoped>

</style>
